<template>
  <view class="container">
    <!-- Status bar placeholder -->
    <view :style="{ height: statusBarHeight + 'px' }"></view>
    
    <!-- Top navigation bar -->
    <view class="navbar">
      <view class="navbar-left" @click="goBack">
        <uni-icons type="left" size="20" color="#333"></uni-icons>
      </view>
      <view class="navbar-title">订单详情</view>
      <view class="navbar-right"></view>
    </view>
    
    <!-- Loading -->
    <view v-if="loading" class="loading-container">
      <uni-icons type="spinner-cycle" size="30" color="#FF8C42"></uni-icons>
      <text class="loading-text">加载中...</text>
    </view>
    
    <!-- Order detail content -->
    <view v-else-if="orderDetail" class="order-detail">
      <!-- Retail Shelf Address - Replacing Status Section -->
      <view class="status-section shelf-address-section">
        <view class="shelf-icon">
          <uni-icons type="location-filled" size="32" color="#FF8C42"></uni-icons>
        </view>
        <view class="shelf-info">
          <view class="shelf-title">零售货架地址</view>
          <view class="shelf-address">{{ getShelfAddress() }}</view>
        </view>
      </view>
      
      <!-- Shipping address -->
      <view class="address-section">
        <view class="section-title">
          <uni-icons type="location" size="16" color="#FF8C42"></uni-icons>
          <text>你的地址</text>
        </view>
        <view class="address-content" v-if="orderDetail.shipping">
          <view class="address-name">{{ orderDetail.shipping.receiverName }} {{ orderDetail.shipping.receiverPhone }}</view>
          <view class="address-detail">{{ orderDetail.shipping.receiverAddress }}</view>
        </view>
        <view class="address-content" v-else>
          <text class="no-data">暂无收货地址信息</text>
        </view>
      </view>
      
      <!-- Order information -->
      <view class="order-info-section">
        <view class="section-title">
          <uni-icons type="info" size="16" color="#FF8C42"></uni-icons>
          <text>订单信息</text>
        </view>
        <view class="info-item">
          <text class="info-label">订单编号</text>
          <text class="info-value">{{ orderDetail.order.orderNo }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">创建时间</text>
          <text class="info-value">{{ formatDate(orderDetail.order.createTime) }}</text>
        </view>
        <view class="info-item" v-if="orderDetail.order.paymentTime">
          <text class="info-label">支付时间</text>
          <text class="info-value">{{ formatDate(orderDetail.order.paymentTime) }}</text>
        </view>
        <view class="info-item" v-if="orderDetail.order.paymentType">
          <text class="info-label">支付方式</text>
          <text class="info-value">{{ getPaymentTypeText(orderDetail.order.paymentType) }}</text>
        </view>
        <view class="info-item" v-if="orderDetail.order.remark">
          <text class="info-label">订单备注</text>
          <text class="info-value">{{ orderDetail.order.remark }}</text>
        </view>
      </view>
      
      <!-- Product list -->
      <view class="products-section">
        <view class="section-title">
          <uni-icons type="shop" size="16" color="#FF8C42"></uni-icons>
          <text>商品信息</text>
        </view>
        <view v-if="orderDetail.orderItems && orderDetail.orderItems.length > 0">
          <view 
            v-for="(item, index) in orderDetail.orderItems" 
            :key="index"
            class="product-item"
          >
            <image class="product-image" :src="imageFullUrl(item.productImage)" mode="aspectFill"></image>
            <view class="product-info">
              <view class="product-name">{{ item.productName }}</view>
              <view class="product-price">
                <text class="price">¥{{ item.unitPrice }}</text>
                <text class="quantity">x{{ item.quantity }}</text>
              </view>
            </view>
          </view>
        </view>
        <view v-else class="no-products">
          <text class="no-data">暂无商品信息</text>
        </view>
      </view>
      
      <!-- Amount information -->
      <view class="amount-section">
        <view class="amount-item">
          <text>商品总额</text>
          <text>¥{{ orderDetail.order.totalAmount }}</text>
        </view>
        <view class="amount-item">
          <text>运费</text>
          <text>¥0.00</text>
        </view>
        <view class="amount-divider"></view>
        <view class="amount-item total">
          <text>实付款</text>
          <text class="total-amount">¥{{ orderDetail.order.totalAmount }}</text>
        </view>
      </view>
      
      <!-- Bottom action buttons -->
      <view class="footer-actions">
        <!-- Different action buttons based on order status -->
       <!-- <template v-if="orderDetail.order.status === 0">
          <button class="action-btn cancel-btn" @click="cancelOrder(orderDetail.order.orderNo)">取消订单</button>
          <button class="action-btn primary-btn" @click="payOrder(orderDetail.order.orderNo, orderDetail.order.totalAmount)">去支付</button>
        </template> -->
        <template v-if="orderDetail.order.status === 1">
          <button class="action-btn primary-btn" @click="reorderItems(orderDetail.order.orderNo)">再来一单</button>
        </template>
        <template v-else-if="orderDetail.order.status === 2">
          <button class="action-btn primary-btn" @click="confirmReceipt(orderDetail.order.orderNo)">确认收货</button>
        </template>
        <template v-else-if="orderDetail.order.status === 3">
          <button class="action-btn primary-btn" @click="rateOrder(orderDetail.order.orderNo)">评价订单</button>
        </template>
      </view>
    </view>
    
    <!-- Order not found -->
    <view v-else class="not-found">
      <image class="not-found-image" src="/static/not-found.png" mode="aspectFit"></image>
      <text class="not-found-text">订单不存在或已被删除</text>
      <button class="go-back-btn" @click="goBack">返回</button>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useUserStore } from '@/store/user';
import { useCartStore } from '@/store/cart';
import http from '@/utils/http/http.js';
import { getImageUrl } from '@/config/env';

const userStore = useUserStore();
const cartStore = useCartStore();
const statusBarHeight = ref(0);
const loading = ref(true);
const orderDetail = ref(null);
const orderNo = ref('');

// Generate full image URL
const imageFullUrl = (path) => {
  if (!path) return '/static/placeholder.png';
  return getImageUrl(path);
};

// Get status bar height
const getStatusBarHeight = () => {
  try {
    const systemInfo = uni.getSystemInfoSync();
    statusBarHeight.value = systemInfo.statusBarHeight || 0;
  } catch (e) {
    console.error('Failed to get system info:', e);
    statusBarHeight.value = 0;
  }
};

// Get shelf address based on order
const getShelfAddress = () => {
  // This would normally come from the API, but for now we'll return a placeholder
  // You can replace this with actual data from your API when available
  return "湖南农业大学芷兰学生公寓B栋附近";
};

// Go back to previous page
const goBack = () => {
  uni.navigateBack();
};

// Get order details
const getOrderDetail = async () => {
  loading.value = true;
  
  try {
    // Check login status
    if (!userStore.isLoggedIn || !userStore.token) {
      uni.showToast({
        title: '请先登录',
        icon: 'none'
      });
      uni.navigateBack();
      return;
    }
    
    // Send request
    const response = await http.get(`/api/orders/detail/${orderNo.value}`, {
      header: {
        'Authorization': `Bearer ${userStore.token}`
      }
    });
    
    if (response.code === 200 && response.data) {
      console.log('Order detail data:', response.data);
      orderDetail.value = response.data;
    } else {
      uni.showToast({
        title: response.message || '获取订单详情失败',
        icon: 'none'
      });
      orderDetail.value = null;
    }
  } catch (error) {
    console.error('Failed to get order details:', error);
    uni.showToast({
      title: '获取订单详情失败，请重试',
      icon: 'none'
    });
    orderDetail.value = null;
  } finally {
    loading.value = false;
  }
};

// Cancel order
const cancelOrder = async (orderNo) => {
  uni.showModal({
    title: '提示',
    content: '确定要取消该订单吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          const response = await http.post(`/api/orders/cancel/${orderNo}`, {}, {
            header: {
              'Authorization': `Bearer ${userStore.token}`
            }
          });
          
          if (response.code === 200) {
            uni.showToast({
              title: '订单已取消',
              icon: 'success'
            });
            
            // Reload order details
            getOrderDetail();
          } else {
            uni.showToast({
              title: response.message || '取消订单失败',
              icon: 'none'
            });
          }
        } catch (error) {
          console.error('Failed to cancel order:', error);
          uni.showToast({
            title: '取消订单失败，请重试',
            icon: 'none'
          });
        }
      }
    }
  });
};

// Pay for order
const payOrder = (orderNo, amount) => {
  uni.navigateTo({
    url: `/pages/orders/payment?orderNo=${orderNo}&amount=${amount}`
  });
};

// Reorder items (new implementation)
const reorderItems = async (orderNo) => {
  try {
    uni.showLoading({
      title: '处理中...'
    });
    
    if (!orderDetail.value || !orderDetail.value.orderItems || orderDetail.value.orderItems.length === 0) {
      uni.showToast({
        title: '订单商品信息不存在',
        icon: 'none'
      });
      return;
    }
    
    // Clear cart first (optional, based on business requirements)
    // await cartStore.clearCart();
    
    // Add each item to cart
    let addedCount = 0;
    for (const item of orderDetail.value.orderItems) {
      // Create product object from order item
      const product = {
        id: item.productId,
        name: item.productName,
        price: item.unitPrice,
        mainImageUrl: item.productImage,
        status: 1, // Assume product is available
        totalStock: 999, // Assume sufficient stock
        spec: item.productSpec || ''
      };
      
      // Add to cart
      const success = await cartStore.addToCart(product, item.quantity);
      if (success) {
        addedCount++;
      }
    }
    
    uni.hideLoading();
    
    if (addedCount > 0) {
      uni.showToast({
        title: '已添加到购物车',
        icon: 'success'
      });
      
      // Navigate to cart page
      setTimeout(() => {
        uni.switchTab({
          url: '/pages/cart/cart'
        });
      }, 1500);
    } else {
      uni.showToast({
        title: '添加商品失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('再来一单失败:', error);
    uni.hideLoading();
    uni.showToast({
      title: '操作失败，请重试',
      icon: 'none'
    });
  }
};

// Confirm receipt
const confirmReceipt = async (orderNo) => {
  uni.showModal({
    title: '提示',
    content: '确认已收到商品吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          const response = await http.post(`/api/orders/confirm/${orderNo}`, {}, {
            header: {
              'Authorization': `Bearer ${userStore.token}`
            }
          });
          
          if (response.code === 200) {
            uni.showToast({
              title: '确认收货成功',
              icon: 'success'
            });
            
            // Reload order details
            getOrderDetail();
          } else {
            uni.showToast({
              title: response.message || '确认收货失败',
              icon: 'none'
            });
          }
        } catch (error) {
          console.error('Failed to confirm receipt:', error);
          uni.showToast({
            title: '确认收货失败，请重试',
            icon: 'none'
          });
        }
      }
    }
  });
};

// Rate order
const rateOrder = (orderNo) => {
  uni.navigateTo({
    url: `/pages/orders/rate?orderNo=${orderNo}`
  });
};

// Get order status icon
const getStatusIcon = (status) => {
  switch (status) {
    case 0: return 'wallet';
    case 1: return 'shop';
    case 2: return 'car';
    case 3: return 'checkmark-circle';
    case 4: return 'close-circle';
    default: return 'info';
  }
};

// Get order status text
const getStatusText = (status) => {
  switch (status) {
    case 0: return '待付款';
    case 1: return '待发货';
    case 2: return '待收货';
    case 3: return '已完成';
    case 4: return '已取消';
    default: return '未知状态';
  }
};

// Get order status description
const getStatusDescription = (status) => {
  switch (status) {
    case 0: return '请在24小时内完成支付，否则订单将自动取消';
    case 1: return '商家正在处理您的订单，请耐心等待';
    case 2: return '商品已发出，请注意查收';
    case 3: return '订单已完成，感谢您的购买';
    case 4: return '订单已取消';
    default: return '';
  }
};

// Get payment type text
const getPaymentTypeText = (paymentType) => {
  switch (paymentType) {
    case 1: return '支付宝';
    case 2: return '微信支付';
    case 3: return '银联支付';
    default: return '未知方式';
  }
};

// Format date
const formatDate = (dateString) => {
  if (!dateString) return '';
  
  const date = new Date(dateString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

// Execute on page load
onMounted(() => {
  getStatusBarHeight();
  
  // Get page parameters
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const options = currentPage.$page?.options || {};
  
  if (options.orderNo) {
    orderNo.value = options.orderNo;
    getOrderDetail();
  } else {
    uni.showToast({
      title: '订单号不存在',
      icon: 'none'
    });
    setTimeout(() => {
      uni.navigateBack();
    }, 1500);
  }
});
</script>

<style>
.container {
  background-color: #FFF9F2;
  min-height: 100vh;
}

.navbar {
  display: flex;
  align-items: center;
  height: 44px;
  background-color: #fff;
  border-bottom: 1px solid #eee;
  padding: 0 15px;
}

.navbar-left {
  width: 40px;
}

.navbar-title {
  flex: 1;
  text-align: center;
  font-size: 16px;
  font-weight: bold;
}

.navbar-right {
  width: 40px;
}

.loading-container, .not-found {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 100px 0;
}

.loading-text, .not-found-text {
  margin-top: 15px;
  font-size: 14px;
  color: #999;
}

.not-found-image {
  width: 120px;
  height: 120px;
  margin-bottom: 10px;
}

.go-back-btn {
  margin-top: 20px;
  background: linear-gradient(to right, #FF8C42, #FF9F1C);
  color: #fff;
  border: none;
  border-radius: 20px;
  font-size: 14px;
  padding: 5px 20px;
}

.order-detail {
  padding-bottom: 100px; /* Space for bottom buttons */
}

/* Retail Shelf Address Section - New Styles */
.shelf-address-section {
  display: flex;
  align-items: center;
  padding: 20px 15px;
  background-color: #fff;
  margin-bottom: 10px;
}

.shelf-icon {
  margin-right: 15px;
}

.shelf-info {
  flex: 1;
}

.shelf-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}

.shelf-address {
  font-size: 14px;
  color: #666;
  line-height: 1.5;
}

.address-section, .order-info-section, .products-section, .amount-section {
  background-color: #fff;
  margin: 0 10px 10px;
  border-radius: 10px;
  padding: 15px;
}

.section-title {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  font-size: 15px;
  font-weight: bold;
  color: #333;
}

.section-title uni-icons {
  margin-right: 5px;
}

.address-content {
  padding-left: 5px;
}

.address-name {
  font-size: 15px;
  font-weight: bold;
  margin-bottom: 5px;
}

.address-detail {
  font-size: 13px;
  color: #666;
  line-height: 1.5;
}

.info-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  font-size: 13px;
}

.info-label {
  color: #666;
}

.info-value {
  color: #333;
}

.product-item {
  display: flex;
  padding: 10px 0;
  border-bottom: 1px solid #f5f5f5;
}

.product-item:last-child {
  border-bottom: none;
}

.product-image {
  width: 80px;
  height: 80px;
  border-radius: 5px;
  margin-right: 10px;
  background-color: #f5f5f5;
}

.product-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.product-name {
  font-size: 14px;
  color: #333;
  margin-bottom: 5px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.product-price {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.price {
  font-size: 15px;
  color: #FF8C42;
  font-weight: bold;
}

.quantity {
  font-size: 13px;
  color: #999;
}

.amount-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  font-size: 14px;
  color: #666;
}

.amount-divider {
  height: 1px;
  background-color: #f5f5f5;
  margin: 10px 0;
}

.total {
  font-weight: bold;
  color: #333;
}

.total-amount {
  color: #FF8C42;
  font-size: 16px;
}

.footer-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  justify-content: flex-end;
  padding: 10px 15px;
  background-color: #fff;
  border-top: 1px solid #eee;
  gap: 10px;
}

.action-btn {
  font-size: 14px;
  padding: 6px 15px;
  border-radius: 20px;
  background-color: #fff;
  color: #666;
  border: 1px solid #ddd;
}

.primary-btn {
  background: linear-gradient(to right, #FF8C42, #FF9F1C);
  color: #fff;
  border: none;
}

.cancel-btn {
  border: 1px solid #FF8C42;
  color: #FF8C42;
  background-color: #fff;
}

.no-data {
  color: #999;
  font-size: 13px;
}

.no-products {
  padding: 20px 0;
  text-align: center;
}
</style>